import os
from docx import Document
from docx.shared import Inches
from PyPDF4 import PdfFileMerger
import comtypes.client


class BaoXiao:
    def image_to_word_pdf_merge(self, path):
        items = os.listdir(path)
        pdfs_path = []
        for dir in items:
            # 构建完整的路径
            full_path = os.path.join(path, dir)
            # 判断是否是目录
            if os.path.isdir(full_path):
                print("正在处理 " + dir + " ......")
                files = os.listdir(full_path)
                # 图片路径
                imagesPath = []
                document = Document()
                # 遍历和过滤图片
                for file in files:
                    if file.endswith(".png") or file.endswith(".jpg"):
                        print("正在处理 " + file + " 中.....")
                        imagePath = full_path + "\\" + file
                        imagesPath.append(imagePath)
                        document.add_picture(imagePath, width=Inches(6), height=Inches(4))
                # word保存路径
                docx_path = full_path + "\\" + dir + ".docx"
                # pdf保存路径
                pdf_path = full_path + "\\" + dir + ".pdf"
                if (os.path.exists(docx_path)):
                    os.remove(docx_path)
                if (os.path.exists(pdf_path)):
                    os.remove(pdf_path)
                document.save(docx_path)
                word = comtypes.client.CreateObject('Word.Application')
                doc = word.Documents.Open(docx_path)
                doc.SaveAs(pdf_path, FileFormat=17)  # 17 是 PDF 的格式代码
                doc.Close()
                word.Quit()
                pdfs_path.append(pdf_path)

        merger = PdfFileMerger()
        for pdf in pdfs_path:
            merger.append(pdf)
        output_path = os.path.join(path, "合并pdf.pdf")
        merger.write(output_path)
        merger.close()
        input("合并完毕!")


if __name__ == '__main__':
    baoXiao = BaoXiao()
    path = input("输入图片文件夹路径:")
    baoXiao.image_to_word_pdf_merge(path)
